#include "profilewidget.h"
#include "ui_profilewidget.h"
#include "changepassworddialog.h"
#include <QDateTime>

ProfileWidget::ProfileWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ProfileWidget)
{
    ui->setupUi(this);
    
    // 连接信号槽
    connect(ui->changePasswordBtn, &QPushButton::clicked, this, &ProfileWidget::onChangePasswordClicked);
    connect(ui->refreshBtn, &QPushButton::clicked, this, &ProfileWidget::onRefreshClicked);
}

ProfileWidget::~ProfileWidget()
{
    delete ui;
}

void ProfileWidget::setCurrentUser(const UserInfo& userInfo)
{
    m_currentUser = userInfo;
    loadUserInfo();
}

void ProfileWidget::refreshUserInfo()
{
    // 从数据库重新获取用户信息
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    
    // 根据用户ID重新查询用户信息
    QSqlQuery query(dbManager.getDatabase());
    query.prepare("SELECT username, role, created_at FROM users WHERE id = ?");
    query.addBindValue(m_currentUser.id);
    
    if (query.exec() && query.next()) {
        m_currentUser.username = query.value("username").toString();
        m_currentUser.role = query.value("role").toString();
        m_currentUser.createdAt = query.value("created_at").toString();
        
        loadUserInfo();
    } else {
        QMessageBox::warning(this, "错误", "无法获取用户信息！");
    }
}

void ProfileWidget::onChangePasswordClicked()
{
    ChangePasswordDialog dialog(m_currentUser, this);
    // 连接密码修改成功信号
    connect(&dialog, &ChangePasswordDialog::passwordChangedSuccessfully, 
            this, &ProfileWidget::onPasswordChanged);
    
    dialog.exec();
    // 不再需要显示成功提示，因为会自动退出登录
}

void ProfileWidget::onRefreshClicked()
{
    refreshUserInfo();
    QMessageBox::information(this, "提示", "信息已刷新！");
}

void ProfileWidget::onPasswordChanged()
{
    // 密码修改成功后直接退出登录
    emit logoutRequired();
}

void ProfileWidget::loadUserInfo()
{
    // 显示用户名
    ui->usernameValueLabel->setText(m_currentUser.username);
    
    // 显示用户角色
    QString roleText = (m_currentUser.role == "admin") ? "管理员" : "普通用户";
    ui->roleValueLabel->setText(roleText);
    
    // 显示注册时间（从数据库获取真实时间）
    ui->createTimeValueLabel->setText(m_currentUser.createdAt.isEmpty() ? "未知" : m_currentUser.createdAt);
    
    // 显示最后登录时间（当前时间）
    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    ui->lastLoginValueLabel->setText(currentTime);
}